package cn.ren.cloud.controller;

import cn.ren.cloud.service.ITeacherService;
import cn.ren.cloud.domain.Teacher;
import cn.ren.cloud.query.TeacherQuery;
import cn.ren.cloud.result.JsonResult;
import cn.ren.cloud.result.PageList;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author 23508
 */
@RestController
@RequestMapping("/teacher")
public class TeacherController {

    public final ITeacherService teacherService;

    public TeacherController(ITeacherService teacherService) {
        this.teacherService = teacherService;
    }

    /**
     * 保存和修改公用的
     */
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public JsonResult saveOrUpdate(@RequestBody Teacher teacher) {
        if (teacher.getId() != null) {
            teacherService.updateById(teacher);
        } else {
            teacherService.insert(teacher);
        }
        return JsonResult.success();
    }

    /**
     * 删除对象
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    public JsonResult delete(@PathVariable("id") Long id) {
        teacherService.deleteById(id);
        return JsonResult.success();
    }

    /**
     * 批量删除对象
     */
    @PatchMapping
    public JsonResult batchRemove(@RequestBody List<Long> ids) {
        teacherService.batchRemove(ids);
        return JsonResult.success();
    }

    /**
     * 获取对象
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public JsonResult get(@PathVariable("id") Long id) {
        return JsonResult.success(teacherService.selectById(id));
    }


    /**
     * 查询所有对象
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public JsonResult list() {
        return JsonResult.success(teacherService.selectList(null));
    }


    /**
     * 带条件分页查询数据
     */
    @RequestMapping(value = "/pageList", method = RequestMethod.POST)
    public JsonResult page(@RequestBody TeacherQuery query) {
        Page<Teacher> page = new Page<>(query.getPage(), query.getRows());
        if (query.getKeyword() != null && query.getKeyword().length() != 0) {
            EntityWrapper<Teacher> wrapper = new EntityWrapper<>();
            wrapper.like("name", query.getKeyword());
            page = teacherService.selectPage(page, wrapper);
            return JsonResult.success(new PageList<>(page.getTotal(), page.getRecords()));
    }
        page = teacherService.selectPage(page);
        return JsonResult.success(new PageList<>(page.getTotal(), page.getRecords()));
    }
}
